// pages/search/search.js
const app = getApp();
var util = require("../../utils/util");
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    searchValue: "", //input输入的内容
    hotShow: true, //热门搜索显示
    historyShow: true, //历史搜索显示
    shishiShow: false, //实时搜索显示
    resultShow: false, //搜索结果显示
    shishiData: [], //实时搜索结果
    songResultData: [], //歌曲搜索结果
    singerResultData: [], //歌手搜索结果
    pipeiData: [], //最匹配的歌手
    historyData: [], //历史搜索结果
    hotData: [], //热门搜索

    token: "",
    headurl: "",
    songpage: 1, //歌曲当前页码
    singerpage: 1, //歌手当前页码
    songlastpage: "", //歌曲总共页码
    singerlastpage: "", //歌手总共页码
  },
  // 播放歌曲
  play(e) {
    var that = this;
    console.log(e.currentTarget.dataset.code);
    // var token = wx.getStorageSync("token");
    var code = e.currentTarget.dataset.code;
    var tempParam = {
      code: code,
    };
    if (that.data.token) {
      util.postToken("/wechat/play", tempParam, that.data.token, function (
        res
      ) {
        console.log(res.status_code, "播放");
        if (res.status_code == 200) {
          Toast.success("成功");
        } else if (res.status_code == 1002) {
          console.log(res);
          // 播放歌曲接口调用websocket服务出错：ch==null,设备没经过握手
          Toast("电视未连接");
        } else {
          // Toast(res.msg);
        }
      });
    }
  },
  // 添加歌曲
  add(e) {
    var that = this;
    var codes = e.currentTarget.dataset.code;
    var uid = app.globalData.uid;
    var tempParam = {
      codes: codes,
      uid: uid,
      headurl: that.data.headurl,
    };
    if (that.data.token) {
      util.postToken(
        "/wechat/playlist/song/add",
        tempParam,
        that.data.token,
        function (res) {
          if (res.status_code == 200) {
            Toast.success("成功");
          } else if (res.status_code == 1002) {
            console.log(res);
            Toast(res.msg);
          } else {
            Toast(res.msg);
          }
          console.log(res);
        }
      );
    } else {
    }
  },
  // 收藏歌曲
  love(e) {
    var that = this;
    var songCode = e.currentTarget.dataset.code;
    // var token = wx.getStorageSync("token");
    var tempParam = {
      songCode: songCode,
    };
    if (that.data.token) {
      util.postToken(
        "/wechat/song/favorites/add",
        tempParam,
        that.data.token,
        function (res) {
          if (res.status_code == 200) {
            Toast.success("收藏成功");
          } else if (res.status_code == 1002) {
            console.log(res);
            Toast(res.msg);
          } else {
            Toast(res.msg);
          }
          console.log(res, "收藏");
        }
      );
    }
  },
  // input输入时
  input: function (e) {
    var that = this;
    if (e.detail.value == "") {
      that.setData({
        searchValue: "",
        hotShow: true,
        historyShow: true,
        shishiShow: false,
        resultShow: false,
      });
    } else {
      that.setData({
        searchValue: e.detail.value,
        hotShow: false,
        historyShow: false,
        shishiShow: true,
        resultShow: false,
      });

      let params = {
        keyword: that.data.searchValue,
        per_page: 20,
        page: 1,
      };
      util.postHeader("/search", JSON.stringify(params), function (res) {
        that.setData({
          shishiData: res.data.songs.data,
        });
        console.log(res.data, "111");
      });
    }
  },
  // getData(){
  //   var that=this
  //   let params={
  //     keyword:that.data.searchValue,
  //     per_page: 20,
  //     page:  1,
  //   }
  //   util.postHeader('/search',JSON.stringify(params),function (res) {
  //     // console.log(res.data,'111')
  //     if (res.status_code==200) {
  //       that.setData({
  //         requestData:res.data
  //       })
  //     }
  //   })
  // },
  onSearch(e) {
    var that = this;
    that.setData({
      hotShow: false,
      historyShow: false,
      shishiShow: false,
      resultShow: true,
    });
    let params = {
      keyword: that.data.searchValue,
      per_page: 20,
      page: 1,
    };
    util.postHeader("/search", JSON.stringify(params), function (res) {
      console.log(res.data.songs);
      if (res.status_code == 200) {
        that.setData({
          songResultData: res.data.songs.data,
          songpage: res.data.songs.current_page, //歌曲当前页码
          songlastpage: res.data.songs.last_page, //歌曲总共页码
          singerResultData: res.data.singers.data,
          singerpage: res.data.singers.current_page, //歌手当前页码
          singerlastpage: res.data.singers.last_page, //歌手总共页码
          pipeiData: [res.data.singers.data[0]] || [],
        });
      }
    });
  },
  // input确认输入时
  // from,有from代表有传入的值
  inputConfirm: function (e) {
    var that = this;
    that.setData({
      searchValue: e.detail.value,
    });
    that.onSearch(that.data.searchValue);
    that.setflash(that.data.searchValue);
  },
  // 实时搜索结果点击
  shishiClick(e) {
    this.setData({
      searchValue: e.currentTarget.dataset.name,
    });

    this.onSearch(e.currentTarget.dataset.name, "shishi");
    this.setflash(e.currentTarget.dataset.name);
  },
  // 搜索历史点击
  clickHistory(e) {
    this.setData({
      searchValue: e.currentTarget.dataset.name,
    });

    this.onSearch(e.currentTarget.dataset.name);
  },
  // 热门搜索点击
  clickHot(e) {
    this.setData({
      searchValue: e.currentTarget.dataset.name,
    });
    this.onSearch(e.currentTarget.dataset.name);
    this.setflash(e.currentTarget.dataset.name);
  },
  // 取消搜索
  cancelSearch() {
    var that = this;
    that.setData({
      searchValue: "",
      hotShow: true,
      historyShow: true,
      shishiShow: false,
      resultShow: false,
    });
  },
  // 从缓存中更新搜索历史
  reflash() {
    var that = this;
    wx.getStorage({
      key: "searchHistory",
      success(res) {
        console.log(res.data);
        that.setData({
          historyData: res.data,
        });
      },
      fail() {
        console.log("失败");
        that.setData({
          historyData: [],
        });
      },
    });
  },
  // 将搜索记录添加到缓存中
  setflash(e) {
    var that = this;
    var dataArr = that.data.historyData;
    // console.log(typeof that.data.historyData);
    dataArr.push(e);
    if (dataArr.length > 3) {
      dataArr.splice(0, Number(dataArr.length) - 3);
    } else {
    }
    that.setData({
      historyData: dataArr,
    });
    wx.setStorage({
      key: "searchHistory",
      data: that.data.historyData,
    });
  },
  // 清除所有记录
  alldel() {
    wx.clearStorage();
    this.reflash();
  },
  //清除某一条记录
  delthis(e) {
    console.log(e.currentTarget.dataset.index);
    var that = this;
    var dataArr = that.data.historyData;
    dataArr.splice(e.currentTarget.dataset.index, 1);
    wx.setStorage({
      key: "searchHistory",
      data: dataArr,
    });
    this.reflash();
  },
  // 跳转歌星主页
  bindNavView(e) {
    console.log(e.currentTarget.dataset.name);
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    let imgurl = e.currentTarget.dataset.imgurl;
    wx.navigateTo({
      // url: "../singerIndex/singerIndex",
      url:
        "../singerIndex/singerIndex?id=" +
        id +
        "&name=" +
        name +
        "&imgurl=" +
        imgurl,
    });
  },
  // 跳转歌曲反馈
  gotoFeedback(){
    wx.navigateTo({
      url: '../my/songFeedback/songFeedback',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.reflash();
    that.setData({
      token: app.globalData.token,
      headurl: wx.getStorageSync("wxImg"),
    });
    util.postRes("/common/config/hot_keyword", {}, function (res) {
      that.setData({
        hotData: res.data,
      });
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //重新获取缓存
    var that = this;
    that.reflash();
    that.setData({
      token: wx.getStorageSync("token"),
      headurl: wx.getStorageSync("wxImg"),
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onChange(event){
    console.log(event.detail.index)
    this.setData({
      currentTab:event.detail.index
    })
  },
  onReachBottom: function () {
    var that = this;

    if (that.data.currentTab == 0) {
      console.log("触发1");
      if (
        that.data.songlastpage &&
        that.data.songpage <= that.data.songlastpage
      ) {
        let params = {
          keyword: that.data.searchValue,
          per_page: 20,
          page: that.data.songpage + 1,
        };
        util.postHeader("/search", JSON.stringify(params), function (res) {
          console.log(res.data.songs);
          if (res.status_code == 200) {
            that.setData({
              songResultData:that.data.songResultData.concat(res.data.songs.data) ,
              songpage: res.data.songs.current_page,
              songlastpage: res.data.songs.last_page,
              // pipeiData: [res.data.singers.data[0]] || [],
            });
          }
        });
      }
    } else {
      console.log("触发2");
      if (
        that.data.singerlastpage &&
        that.data.singerpage <= that.data.singerlastpage
      ) {
        let params = {
          keyword: that.data.searchValue,
          per_page: 20,
          page: that.data.singerpage + 1,
        };
        util.postHeader("/search", JSON.stringify(params), function (res) {
          console.log(res.data.songs);
          if (res.status_code == 200) {
            that.setData({
              singerResultData:that.data.singerResultData.concat(res.data.singers.data),
              singerpage: res.data.singers.current_page,
              singerlastpage: res.data.singers.last_page,
              // pipeiData: [res.data.singers.data[0]] || [],
            });
          }
        });
      }
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
